package ding_talk

import (
	"encoding/json"
	"github.com/gin-gonic/gin"
	"net/http"
	"webhookadapter/app/controllers"
	"webhookadapter/internal"
)

type ControllerDingTalk struct {
}

func (CDT *ControllerDingTalk) Router(engine *gin.Engine, contextPath string) {
	dingTalkGroup := engine.Group(contextPath)
	{
		dingTalkGroup.POST("/dingtalk/send", dingTalkSend)
	}
}

func dingTalkSend(ctx *gin.Context) {
	var msgData controllers.AlertManageMsgData
	var dingTalkMsg controllers.DingTalkMsg
	var alertMsg string
	request, err := ctx.GetRawData()
	if err != nil {
		internal.Logger.Errorf("获取请求体失败: %s", err)
	}
	// 测试数据
	request = []byte(internal.AppConfig.DingTalk.Test)
	internal.Logger.Debugf("获取请求体成功: %s", request)
	err = json.Unmarshal(request, &msgData)
	// 将uts时间格式转成cst时间格式
	msgData.Alerts[0].StartsAt = internal.UtcToCst(msgData.Alerts[0].StartsAt)
	msgData.Alerts[0].EndsAt = internal.UtcToCst(msgData.Alerts[0].EndsAt)
	dingTalkMsg.Msgtype = "text"
	// 根据告警、恢复信息解析模板
	if msgData.Status == "resolved" {
		alertMsg, err = internal.ParseTemplate(internal.AppConfig.DingTalk.ResolvedMsgTemplate, msgData.Alerts[0])
	} else {
		alertMsg, err = internal.ParseTemplate(internal.AppConfig.DingTalk.AlertMsgTemplate, msgData.Alerts[0])
	}
	if err != nil {
		internal.Logger.Errorf("模板解析失败：%s", err)
		ctx.JSON(http.StatusOK, "发送失败")
		return
	}
	internal.Logger.Infof("模板解析的结果：%s", alertMsg)
	// 发送消息到钉钉
	dingTalkMsg.Text.Content = alertMsg
	jsonMsg, err := json.Marshal(&dingTalkMsg)
	requestService := internal.RequestMethod{}
	res, err := requestService.Post(internal.AppConfig.DingTalk.Url, []byte(jsonMsg))
	if err != nil {
		internal.Logger.Errorf("消息发送到钉钉失败：%s", err)
	}
	internal.Logger.Infof("信息发送成功：%s", res)
	ctx.JSON(http.StatusOK, "发送成功")
}
